/**
 * 下雨组件
 * @returns
 */
function init() {
  let STROKE = 0.08,
    TAU = 2.0 * Math.PI;
  //   TWO_OVER_SQRT_2 = 2.0 / Math.sqrt(2);
  function circle(ctx, x, y, r) {
    ctx.beginPath();
    ctx.arc(x, y, r, 0, TAU, false);
    ctx.fill();
  }
  function puff(ctx, t, cx, cy, rx, ry, rmin, rmax) {
    var c = Math.cos(t * TAU),
      s = Math.sin(t * TAU);

    rmax -= rmin;

    circle(
      ctx,
      cx - s * rx,
      cy + c * 0.35 * ry + rmax * 0.5,
      rmin + (1 - c * 0.5) * rmax
    );
  }
  function puffs(ctx, t, cx, cy, rx, ry, rmin, rmax) {
    var i;

    for (i = 5; i--; ) puff(ctx, t + i / 5, cx, cy, rx, ry, rmin, rmax);
  }

  function cloudObject(ctx, t, cx, cy, cw, s, color) {
    t /= 30000;

    var a = cw * 0.21,
      b = cw * 0.12,
      c = cw * 0.24,
      d = cw * 0.28;

    ctx.fillStyle = color;
    puffs(ctx, t, cx, cy, a, b, c, d);
    ctx.fillStyle = "#999";
    puffs(ctx, t, cx, cy, a, b, c - s, d - s);
    ctx.globalCompositeOperation = "source-over";
  }

  function RAIN(ctx, t, dotColor, clodColor) {
    var w = ctx.canvas.width,
      h = ctx.canvas.height,
      s = Math.min(w, h);

    rainObject(ctx, t, w * 0.5, h * 0.37, s * 0.9, s * STROKE, dotColor);
    cloudObject(ctx, t, w * 0.5, h * 0.37, s * 0.9, s * STROKE, clodColor);
  }

  function rainObject(ctx, t, cx, cy, cw, s, color) {
    t /= 1350;

    var a = cw * 0.16,
      b = (TAU * 11) / 12,
      c = (TAU * 7) / 12,
      i,
      p,
      x,
      y;

    ctx.fillStyle = color;

    for (i = 4; i--; ) {
      p = (t + i / 4) % 1;
      x = cx + ((i - 1.5) / 1.5) * (i === 1 || i === 2 ? -1 : 1) * a;
      y = cy + p * p * cw;
      ctx.beginPath();
      ctx.moveTo(x, y - s * 1.5);
      ctx.arc(x, y, s * 0.75, b, c, false);
      ctx.fill();
    }
  }

  function RainSymbol(_size, _anchor) {
    BMapGL.Symbol.call(this, _size, _anchor);
    this.width = _size.width;
    this.height = _size.height;
    // 需要再addOverlay之前设置true，需要保证纹理大小不变化
    this.isReDraw = true;
  }

  RainSymbol.prototype = new BMapGL.Symbol();
  RainSymbol.prototype.constructor = RainSymbol;

  RainSymbol.prototype.add = function () {
    const canvas = document.createElement("canvas");
    canvas.width = this.width * 2;
    canvas.height = this.height * 2;
    this.context = canvas.getContext("2d");
    // this.isReDraw = false;
  };

  RainSymbol.prototype.render = function () {
    this.context.clearRect(0, 0, this.width * 2, this.height * 2);
    var time = Date.now();
    RAIN(this.context, time, "#BFBFBF", "#999");
    this.data = this.context.getImageData(
      0,
      0,
      this.context.canvas.width,
      this.context.canvas.height
    );
    return true;
  };

  return RainSymbol;
}

export default init;
